using System;
using System.Collections;
using System.Data;
using Sedna.Core.Support;

namespace Sedna.Core.Controller.Configurations
{
	/// <summary>
	/// Summary description for DataGridColumnInboundControlRowValueBasedIdGenerator.
	/// </summary>
	public class DataGridColumnInboundControlRowValueBasedIdGenerator : IDataGridColumnInboundControlIdGenerator
	{
		private IList columns;
		private string suffix = "gridline";
		private bool forceDictionary = false;

		/// <summary>
		/// by default an Id is generated based on a value of a column with "ID" name.
		/// If there is no such column, an Exception is thrown.
		/// </summary>
		public DataGridColumnInboundControlRowValueBasedIdGenerator()
		{
			columns = new ArrayList();
			columns.Add("ID");
		}


		public IList Columns
		{
			get { return columns; }
			set { columns = value; }
		}

		public string Suffix
		{
			get { return suffix; }
			set { suffix = value; }
		}

		public bool ForceDictionary
		{
			get { return forceDictionary; }
			set { forceDictionary = value; }
		}

		public object GenerateId(IDataGridColumnConfiguration columnConfiguration, object dataRow)
		{
			Assert.IsNotNull(dataRow, "dataRow parameter cannot be null");

			DataRowView drv = dataRow as DataRowView;
			if(drv != null)
			{
				return GenerateId(drv);
			}

			throw new NotSupportedException("Only DataRowView Type is supported as an argument of the GenerateId() method. You have passed:" + dataRow.GetType());
		}

		private object GenerateId(DataRowView drv)
		{
			if(columns.Count == 1 && !forceDictionary)
			{
				return drv[(string)columns[0]];
			}
			IDictionary result = new Hashtable();
			foreach(string columnName in columns)
			{
				result.Add(columnName, drv[columnName]);
			}
			return result;
		}
	}
}
